import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shimo_app/bus/struct/task_progress.dart';
import 'package:shimo_app/pages/components/hint.dart';

import '../../services/device_service.dart';
import '../components/baseDialog.dart';
import 'function/function_controller.dart';
import 'function/function_view.dart';
import 'sample_controller.dart';

class SamplePage extends StatelessWidget {
  final double height;
  final double width;
  final String title;

  const SamplePage(
      {Key? key,
      required this.height,
      required this.width,
      required this.title})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 获取SampleController实例并放入依赖注入
    final controller = Get.put(SampleController());
    final state = Get.find<SampleController>().state;

    // 定义表格头部标签
    List<String> weightedHeader = [
      "任务名称",
      "操作项",
      "参数",
      "单位",
      "操作项",
      "参数",
      "单位",
      "操作项",
      "参数",
      "单位",
    ];

    return Container(
      width: width,
      height: height,
      child: GetBuilder<SampleController>(builder: (controller) {
        return Row(
            children: List.generate(
          2, // 生成两个相同的容器（可能是双通道设备界面）
          (containerId) {
            // 定义操作按钮配置
            final operationButtons = [
              {
                "name": controller.working[containerId] ? "运行中" : "开始",
                "icon": Icons.play_arrow,
                "onPress": (controller.working[containerId] ||
                        Get.find<FunctionController>()
                            .useFunctionList[containerId]
                            .isEmpty)
                    ? null // 条件禁用：正在运行或方法列表为空时禁用
                    : () {
                        controller.runTask(containerId);
                      },
              },
              {
                "name": "暂停",
                "icon": Icons.pause,
                "onPress": !controller.working[containerId] ||
                        controller.pause[containerId]
                    ? null // 条件禁用：未运行或已暂停时禁用
                    : () {
                        controller.pauseTask(containerId);
                      },
              },
              {
                "name": "停止",
                "icon": Icons.stop,
                "onPress": !controller.working[containerId] &&
                        !controller.pause[containerId]
                    ? null // 条件禁用：未运行且未暂停时禁用
                    : () {
                        controller.abortTask(containerId);
                      },
              },
              {
                "name": "方法",
                "icon": Icons.assignment,
                "onPress": (controller.working[containerId] ||
                        !controller.busConnected)
                    ? null // 条件禁用：正在运行或总线未连接时禁用
                    : () {
                        // 打开方法配置对话框
                        showBaseDialog(title, const Size(950, 700),
                            FunctionComponent(containerId: containerId),
                            onClose: () {
                          Get.find<FunctionController>().refreshData();
                          return true;
                        });
                      },
              },
              // 日志按钮（暂未实现）
              // {
              //   "name": "日志",
              //   "icon": Icons.description,
              //   "onPress": () {},
              // },
            ];

            return SizedBox(
              width: width / 2, // 每个容器占一半宽度
              child: Column(
                children: [
                  // 标题区域
                  Text(title),

                  // 操作按钮区域
                  SizedBox(
                    height: 50,
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          // 左侧选择按钮组
                          Row(
                            children: [
                              // 全选按钮
                              SizedBox(
                                width: 80,
                                height: 50,
                                child: TextButton(
                                    onPressed: controller.working[containerId]
                                        ? null // 运行时禁用
                                        : () {
                                            controller.selectAll(containerId);
                                          },
                                    child: Text("全选",
                                        style: TextStyle(
                                            fontSize: 20,
                                            fontWeight: FontWeight.bold))),
                              ),
                              //暂时不开放
                              // SizedBox(
                              //   width: 80,
                              //   height: 50,
                              //   child: TextButton(
                              //       onPressed: controller.working[containerId]
                              //           ? null // 运行时禁用
                              //           : () async {
                              //               if (await controller
                              //                   .selectHave(containerId))
                              //                 showHint("成功", HintType.SUCCESS);
                              //               else {
                              //                 showHint("失败", HintType.DANGER);
                              //               }
                              //             },
                              //       child: Text("识别",
                              //           style: TextStyle(
                              //               fontSize: 20,
                              //               fontWeight: FontWeight.bold))),
                              // ),
                              // SizedBox(width: 30),
                              // 全不选按钮
                              SizedBox(
                                width: 80,
                                height: 50,
                                child: TextButton(
                                    onPressed: controller.working[containerId]
                                        ? null // 运行时禁用
                                        : () {
                                            controller.clearAll(containerId);
                                          },
                                    child: Text("清空",
                                        style: TextStyle(
                                            fontSize: 20,
                                            fontWeight: FontWeight.bold))),
                              ),
                            ],
                          ),

                          SizedBox(width: 1),

                          // 右侧操作按钮组
                          Row(
                            children: operationButtons.map((e) {
                              final isStartButton =
                                  (e["name"] as String) == "开始" ||
                                      (e["name"] as String) == "运行中";
                              return Container(
                                margin:
                                    const EdgeInsets.only(left: 2, right: 2),
                                child: ElevatedButton(
                                  onPressed: e["onPress"] == null
                                      ? null
                                      : () {
                                          (e["onPress"] as void Function())();
                                        },
                                  style: ElevatedButton.styleFrom(
                                    // 开始按钮设置更大尺寸
                                    minimumSize: isStartButton
                                        ? const Size(120, 60)
                                        : null,
                                  ),
                                  child: Column(
                                    children: [
                                      Icon(e["icon"] as IconData),
                                      Text(e["name"] as String),
                                    ],
                                  ),
                                ),
                              );
                            }).toList(),
                          ),
                        ]),
                  ),

                  // 主要内容区域
                  Container(
                    height: height / 1.52,
                    width: double.infinity,
                    color: Colors.black12,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 上部区域：样品位网格和日志
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 左侧样品位网格区域
                            Container(
                              padding: EdgeInsets.only(bottom: 2, left: 10),
                              color: Colors.blueAccent,
                              width: width * 38 / 2 / 100, // 占宽度的38%
                              child: Column(
                                children: [
                                  // 样品位网格
                                  Column(
                                    verticalDirection:
                                        VerticalDirection.up, // 从下往上排列
                                    children:
                                        controller.sampleItems[containerId].map(
                                      (e) {
                                        final row = controller
                                            .sampleItems[containerId]
                                            .indexOf(e);
                                        return Row(
                                          textDirection: TextDirection.ltr,
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: e.map((e1) {
                                            final col = e.indexOf(e1);
                                            final label =
                                                (row * e.length + col + 1)
                                                    .toString();
                                            return InkWell(
                                              child:
                                                  GetBuilder<SampleController>(
                                                      builder: (controller) {
                                                return Container(
                                                  alignment: Alignment.center,
                                                  height: 30,
                                                  width: 30,
                                                  margin: EdgeInsets.only(
                                                      left: 3,
                                                      right: 3,
                                                      bottom: 2,
                                                      top: 5),
                                                  decoration: BoxDecoration(
                                                      shape: BoxShape.circle,
                                                      color: e1.selected
                                                          ? Colors
                                                              .orange // 选中状态
                                                          : Colors.white,
                                                      border: e1.state ==
                                                              TaskState.FAULT
                                                          ? Border.all(
                                                              // 故障状态边框
                                                              color: Colors
                                                                  .pinkAccent,
                                                              width: 5.8)
                                                          : (controller
                                                                      .currentTaskProgress[
                                                                          containerId]
                                                                      .pos ==
                                                                  row * e.length +
                                                                      col
                                                              ? Border.all(
                                                                  // 当前执行位置边框
                                                                  color: Colors
                                                                      .lightGreenAccent,
                                                                  width: 5)
                                                              : null)),
                                                  child: Text(label),
                                                );
                                              }),
                                              onTap: controller
                                                      .working[containerId]
                                                  ? null // 运行时禁用点击
                                                  : () {
                                                      e1.selected =
                                                          !e1.selected;
                                                      controller.deviceService
                                                          .addOperationLog(
                                                              containerId,
                                                              "${e1.selected ? '选择' : '取消'}${label}样品位");
                                                      controller.update();
                                                    },
                                            );
                                          }).toList(),
                                        );
                                      },
                                    ).toList(),
                                  ),

                                  SizedBox(height: 8),
                                  Divider(height: 2, color: Colors.white),
                                  SizedBox(height: 2),

                                  // 参数显示区域
                                  // 第一行：温度信息
                                  Padding(
                                    padding: const EdgeInsets.only(
                                        bottom: 4, right: 10),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        // T0 - 设定温度
                                        Expanded(
                                          child: Row(
                                            children: [
                                              Text("T0"),
                                              SizedBox(width: 4),
                                              Container(
                                                alignment: Alignment.center,
                                                width: 55,
                                                height: 20,
                                                color: Colors.white,
                                                child: Text(
                                                  controller.targetTemperatureValue[
                                                              containerId] ==
                                                          0
                                                      ? "0"
                                                      : controller
                                                          .targetTemperatureValue[
                                                              containerId]
                                                          .toStringAsFixed(2),
                                                ),
                                              ),
                                              SizedBox(width: 3),
                                              Text("°C"),
                                            ],
                                          ),
                                        ),
                                        SizedBox(width: 10),
                                        // Ta - 实时温度
                                        Expanded(
                                          child: Row(
                                            children: [
                                              Text("Ta"),
                                              SizedBox(width: 4),
                                              Container(
                                                alignment: Alignment.center,
                                                width: 55,
                                                height: 20,
                                                color: Colors.white,
                                                child: Text(
                                                  controller.currentTemperatureValue[
                                                              containerId] ==
                                                          0
                                                      ? "0"
                                                      : controller
                                                          .currentTemperatureValue[
                                                              containerId]
                                                          .toStringAsFixed(2),
                                                ),
                                              ),
                                              SizedBox(width: 3),
                                              Text("°C"),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  // 第二行：时间信息
                                  Padding(
                                    padding: const EdgeInsets.only(
                                        bottom: 4, right: 10),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        // T - 总时间
                                        Expanded(
                                          child: Row(
                                            children: [
                                              Text("T"),
                                              SizedBox(width: 12),
                                              Container(
                                                alignment: Alignment.center,
                                                width: 55,
                                                height: 20,
                                                color: Colors.white,
                                                child: Text(
                                                  controller.allTime[
                                                              containerId] ==
                                                          0
                                                      ? "0"
                                                      : controller
                                                          .allTime[containerId]
                                                          .toStringAsFixed(0),
                                                ),
                                              ),
                                              SizedBox(width: 3),
                                              Text("min"),
                                            ],
                                          ),
                                        ),
                                        SizedBox(width: 6),
                                        // 剩余时间
                                        Expanded(
                                          child: Row(
                                            children: [
                                              Icon(Icons.hourglass_bottom,
                                                  size: 16), // 漏斗图标
                                              SizedBox(width: 4),
                                              Container(
                                                alignment: Alignment.center,
                                                width: 55,
                                                height: 20,
                                                color: Colors.white,
                                                child: Text(
                                                  controller.remainingtime[
                                                              containerId] ==
                                                          0
                                                      ? "0"
                                                      : controller
                                                          .remainingtime[
                                                              containerId]
                                                          .toStringAsFixed(0),
                                                ),
                                              ),
                                              SizedBox(width: 3),
                                              Text("min"),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  // 第三行：功率和超声波信息
                                  Padding(
                                    padding: const EdgeInsets.only(
                                        bottom: 4, right: 10),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        // P - 功率
                                        Expanded(
                                          child: Row(
                                            children: [
                                              Text("P"),
                                              SizedBox(width: 12),
                                              Container(
                                                alignment: Alignment.center,
                                                width: 55,
                                                height: 20,
                                                color: Colors.white,
                                                child: Text(
                                                  controller.currentHeatPower[
                                                              containerId] ==
                                                          0
                                                      ? "0"
                                                      : controller
                                                          .currentHeatPower[
                                                              containerId]
                                                          .toStringAsFixed(2),
                                                ),
                                              ),
                                              SizedBox(width: 3),
                                              Text("%"),
                                            ],
                                          ),
                                        ),
                                        SizedBox(width: 10),
                                        // H - 超声波值
                                        Expanded(
                                          child: Row(
                                            children: [
                                              Text("H"),
                                              SizedBox(width: 7),
                                              Container(
                                                alignment: Alignment.center,
                                                width: 55,
                                                height: 20,
                                                color: Colors.white,
                                                child: Text(
                                                  controller.currentUltrasonic1[
                                                              containerId] ==
                                                          0
                                                      ? "0"
                                                      : controller
                                                          .currentUltrasonic1[
                                                              containerId]
                                                          .toStringAsFixed(2),
                                                ),
                                              ),
                                              SizedBox(width: 3),
                                              Text("mV"),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  // 第四行：坐标信息
                                  Padding(
                                    padding: const EdgeInsets.only(
                                        bottom: 4, right: 10),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        // X - X轴坐标
                                        Expanded(
                                          child: Row(
                                            children: [
                                              Text("X"),
                                              SizedBox(width: 12),
                                              Container(
                                                alignment: Alignment.center,
                                                width: 55,
                                                height: 20,
                                                color: Colors.white,
                                                child: Text(
                                                  controller.currentArmXPosition[
                                                              containerId] ==
                                                          0
                                                      ? "0"
                                                      : controller
                                                          .currentArmXPosition[
                                                              containerId]
                                                          .toStringAsFixed(2),
                                                ),
                                              ),
                                              SizedBox(width: 3),
                                              Text("mm"),
                                            ],
                                          ),
                                        ),
                                        SizedBox(width: 12),
                                        // Y - Y轴坐标
                                        Expanded(
                                          child: Row(
                                            children: [
                                              Text("Y"),
                                              SizedBox(width: 8),
                                              Container(
                                                alignment: Alignment.center,
                                                width: 55,
                                                height: 20,
                                                color: Colors.white,
                                                child: Text(
                                                  controller.currentArmYPosition[
                                                              containerId] ==
                                                          0
                                                      ? "0"
                                                      : controller
                                                          .currentArmYPosition[
                                                              containerId]
                                                          .toStringAsFixed(2),
                                                ),
                                              ),
                                              SizedBox(width: 3),
                                              Text("mm"),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            // 右侧日志区域
                            Container(
                              height: 330,
                              width: width * 62 / 2 / 100, // 占宽度的62%
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(
                                      color: Colors.black38, width: 2)),
                              padding: EdgeInsets.only(left: 20),
                              child: Column(
                                children: [
                                  Text("日志",
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: 18)),
                                  Expanded(
                                    child: controller.logList.isEmpty
                                        ? Center(
                                            child: Text("暂无数据",
                                                style: TextStyle(
                                                    fontSize: 22,
                                                    color: Colors.grey)),
                                          )
                                        : ListView.builder(
                                            itemBuilder: (context, index) {
                                              // 获取当前日志项
                                              final logItem = controller
                                                  .logList[containerId][index];
                                              // 判断是否为异常日志
                                              final isErrorLog = logItem.type ==
                                                  LogType.errorLog;

                                              return Container(
                                                padding: EdgeInsets.symmetric(
                                                    vertical: 4),
                                                child: Row(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: [
                                                    // 时间戳 - 固定宽度
                                                    Container(
                                                      width: 125,
                                                      child: Text(
                                                        DateTime.fromMillisecondsSinceEpoch(
                                                                logItem.time *
                                                                    1000)
                                                            .toString()
                                                            .substring(0, 19),
                                                        style: TextStyle(
                                                          fontSize: 12,
                                                          color: isErrorLog
                                                              ? Colors.red
                                                              : null, // 异常日志显示红色
                                                        ),
                                                      ),
                                                    ),
                                                    SizedBox(width: 15),
                                                    // 日志类型 - 固定宽度
                                                    Container(
                                                      width: 40,
                                                      child: Text(
                                                        logItem.type ==
                                                                LogType
                                                                    .systemLog
                                                            ? "系统"
                                                            : (logItem.type ==
                                                                    LogType
                                                                        .debugLog
                                                                ? "调试"
                                                                : (logItem.type ==
                                                                        LogType
                                                                            .errorLog
                                                                    ? "异常"
                                                                    : "操作")),
                                                        style: TextStyle(
                                                          fontSize: 12,
                                                          color: isErrorLog
                                                              ? Colors.red
                                                              : null, // 异常日志显示红色
                                                          fontWeight: isErrorLog
                                                              ? FontWeight.bold
                                                              : FontWeight
                                                                  .normal,
                                                        ),
                                                      ),
                                                    ),
                                                    SizedBox(width: 15),
                                                    // 日志内容
                                                    Expanded(
                                                      child: Text(
                                                        logItem.content,
                                                        style: TextStyle(
                                                          fontSize: 12,
                                                          color: isErrorLog
                                                              ? Colors.red
                                                              : null, // 异常日志显示红色
                                                          fontWeight: isErrorLog
                                                              ? FontWeight.bold
                                                              : FontWeight
                                                                  .normal,
                                                        ),
                                                        softWrap: true,
                                                        overflow: TextOverflow
                                                            .visible,
                                                        maxLines: null,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              );
                                            },
                                            shrinkWrap: false,
                                            itemCount: controller
                                                .logList[containerId].length,
                                          ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),

                        SizedBox(width: 10),

                        // 下部区域：方法表格
                        Expanded(
                          child: Container(
                            height: height / 4.5,
                            width: width * 0.499, // 宽度为屏幕一半
                            color: Colors.black12,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                // 表格头部
                                Container(
                                  height: 30,
                                  color: Colors.grey,
                                  child: Row(
                                    children: weightedHeader
                                        .map((e) => Expanded(
                                              child: Center(child: Text(e)),
                                              flex: 1,
                                            ))
                                        .toList(),
                                  ),
                                ),

                                // 表格内容
                                Get.find<FunctionController>()
                                        .useFunctionLabelList[containerId]
                                        .isEmpty
                                    ? Center(
                                        // 无数据提示
                                        child: Text("无数据",
                                            style:
                                                TextStyle(color: Colors.grey)),
                                      )
                                    : Expanded(
                                        child: Scrollbar(
                                          child: GetBuilder<FunctionController>(
                                            builder: (functionController) {
                                              return ListView.separated(
                                                physics:
                                                    const AlwaysScrollableScrollPhysics(), // 强制启用滚动
                                                // 添加以下配置确保触摸滚动正常工作
                                                shrinkWrap: false, // 确保不收缩包裹内容
                                                primary: true, // 启用主滚动控制器
                                                itemBuilder: (context, index) {
                                                  return Container(
                                                    decoration: BoxDecoration(
                                                      border: controller
                                                                  .currentTaskProgress[
                                                                      containerId]
                                                                  .taskId !=
                                                              index
                                                          ? null
                                                          : Border.all(
                                                              color: Colors
                                                                  .lightBlue,
                                                              width: 4,
                                                            ),
                                                    ),
                                                    child: Row(
                                                      children: List.generate(
                                                        weightedHeader.length,
                                                        (index) => index,
                                                      ).map((e) {
                                                        return Expanded(
                                                          child: Center(
                                                            child: Text(
                                                              functionController
                                                                              .useFunctionLabelList[containerId][
                                                                                  index]
                                                                              .length -
                                                                          1 >
                                                                      e
                                                                  ? functionController
                                                                              .useFunctionLabelList[
                                                                          containerId]
                                                                      [index][e]
                                                                  : "-",
                                                            ),
                                                          ),
                                                        );
                                                      }).toList(),
                                                    ),
                                                  );
                                                },
                                                separatorBuilder:
                                                    (BuildContext context,
                                                        int index) {
                                                  return const Divider(
                                                      height: 1.0,
                                                      color: Colors.black12);
                                                },
                                                itemCount: functionController
                                                    .useFunctionLabelList[
                                                        containerId]
                                                    .length,
                                              );
                                            },
                                          ),
                                        ),
                                      )
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        ));
      }),
    );
  }
}
